package voja.android.crvenazvezda;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.BatteryManager;
import android.os.IBinder;
import android.widget.RemoteViews;

public class BatteryReceiver extends Service {
	
	public static final int COLOR_BATTERY_NORMAL = Color.parseColor("#ffffff");
	public static final int COLOR_BATTERY_LOW = Color.parseColor("#d9ac64");
	public static final int COLOR_BATTERY_CRITICAL = Color.parseColor("#ff0000");
	
	private int batterylevel = 0;
	private String batteryStatus ="";
	private int batteryStatus1;
	
	private BroadcastReceiver myReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent){
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_BATTERY_CHANGED)){
				batterylevel = intent.getIntExtra("level", 0);
				int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
				batteryStatus1 = status;
				switch(status){
				case BatteryManager.BATTERY_STATUS_CHARGING:
					batteryStatus = "Charging..."; 
					break;
				case BatteryManager.BATTERY_STATUS_DISCHARGING:
					batteryStatus = "Dis-charging.";
					break;
				case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
					batteryStatus = "Not charging.";
					break;
				case BatteryManager.BATTERY_STATUS_FULL:
					batteryStatus = "Full!";
					break;
				default:
					batteryStatus = "";
					break;
				}
				updateAppWidget(context);
			}
		}
			
		public void updateAppWidget(Context context){
			RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
			updateViews.setTextViewText(R.id.txtBattery, batteryStatus1 == BatteryManager.BATTERY_STATUS_CHARGING ? batteryStatus : batterylevel + "%");
			if( batterylevel < 10){				
				updateViews.setTextColor(R.id.txtBattery, COLOR_BATTERY_CRITICAL);
			}else if(batterylevel < 30){
				updateViews.setTextColor(R.id.txtBattery, COLOR_BATTERY_LOW);
			}else{
				updateViews.setTextColor(R.id.txtBattery, COLOR_BATTERY_NORMAL);
			}
			
			ComponentName myComponentName = new ComponentName(context, WidgetProvider.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(context);
			manager.updateAppWidget(myComponentName, updateViews);
		}
	};
	   
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	public void onCreate() {
		super.onCreate();
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(myReceiver, intentFilter);
	}
	
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(myReceiver);
	}
}
